/**
 *Copyright(c) HNA SYSTEMS Co., LTD
 *
 *@date 2013-7-23
 * 	
 *Original Author: 郑兴(zhengxing)
 *
 *ChangeLog
 *
 */
package com.hnas.sys.web.system;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hnas.core.dto.BaseAjaxResponse;
import com.hnas.core.dto.DTOPagedList;
import com.hnas.core.dto.DataBean;
import com.hnas.sys.core.util.UserUtils;
import com.hnas.sys.domain.PackageStatus;
import com.hnas.sys.orm.MenuPackage;
import com.hnas.sys.service.system.MenuPackageService;
import com.hnas.sys.service.system.criteria.DTOMenuSearch;
import com.hnas.sys.service.system.dto.DTOMenuPackage;
import com.hnas.sys.service.system.dto.DTOUser;

/**
 * @author 郑兴(zhengxing)
 *
 */
@Controller
@RequestMapping("/backend/system/menuPackage")
public class MenuPackageController {
	private Logger log = LoggerFactory.getLogger(MenuPackageController.class);
	private static final Cache cache = CacheManager.getInstance().getCache("systemCache");
	
	@Autowired
	private MenuPackageService menuPackageService;
	
	
	@RequestMapping("/search")
	public String search(ModelMap modelMap, HttpServletRequest request,
			@ModelAttribute("criteria") DTOMenuSearch criteria) {

		try {
//			String page = request.getParameter((new ParamEncoder("values")
//					.encodeParameterName(TableTagParameters.PARAMETER_PAGE)));
//			/**
//			 * if (!"false".equals(request.getParameter("firstInvoke"))) {
//			 * modelMap.put("resultSize", 0); return
//			 * "backend/product/searchProviders"; }
//			 **/
//			if (null == page) {
//				criteria.setPageNo(1);
//			} else {
//				criteria.setPageNo(Integer.parseInt(page));
//			}
			criteria.setTotalCount(-1);
			DTOUser user = UserUtils.getCurrentUser();

			DTOPagedList<DTOMenuPackage> pg = this.menuPackageService.search(criteria);
//			modelMap.put("citys", pg.getList());
			modelMap.put("pg", pg);
			modelMap.put("resultSize", pg.getTotalCount());
			modelMap.put("dto", criteria);
		} catch (Exception e) {
			log.error("", e);
			modelMap.put("resultSize", 0);
		}
		modelMap.put("pageTitle", "主菜单维护");
		List<DataBean> beans = new ArrayList<DataBean>();
		beans.add(new DataBean("name","name","模块名称",false,125));
		beans.add(new DataBean("description","description","描述",true,125));
//		beans.add(new DataBean("statusStr","状态"));
		beans.add(new DataBean("priority","priority","排序","int",true));
		modelMap.put("beans", beans);
		return "backend/system/menu/listMenus";
	}
	@RequestMapping(value = "show/{id}", method = RequestMethod.POST)
	@ResponseBody
	public DTOMenuPackage show(@PathVariable("id") Long id) {
		DTOMenuPackage dto = this.menuPackageService.find(id);
		return dto;
	}

	@RequestMapping(value = "disable/{id}", method = RequestMethod.POST)
	@ResponseBody
	public BaseAjaxResponse disable(@PathVariable("id") Long id) {
		BaseAjaxResponse res = new BaseAjaxResponse();
		try{
			this.menuPackageService.disable(id);
			res.setResult(1);
		} catch (Exception e) {
			res.setErrorMessage(e.getMessage());
		}
		
		return res;
	}
	@RequestMapping(value = "add", method = RequestMethod.POST)
	@ResponseBody
	public BaseAjaxResponse add( DTOMenuPackage dto) {
		BaseAjaxResponse res = new BaseAjaxResponse();
		MenuPackage MenuPackage=this.menuPackageService.getPackgeByName(dto.getName());
		if(null!=MenuPackage&&MenuPackage.getId()>0){
			res.setResult(0);
			res.setErrorMessage("模块已存在!");
			return res;
		}
		return this.save(dto);
	}
	@RequestMapping(value = "save", method = RequestMethod.POST)
	@ResponseBody
	public BaseAjaxResponse save( DTOMenuPackage dto) {
		BaseAjaxResponse res = new BaseAjaxResponse();
		try {
			this.menuPackageService.saveOrUpdate(dto);
			res.setResult(1);
		} catch (Exception e) {
			// TODO Auto-generated catch block
//			e.printStackTrace();
			res.setErrorMessage(e.getMessage());
		}		
		return res;
	}
	/**
	 * <pre>查询菜单包</pre>
	 * @Auther 郑兴(zhengxing)
	 * @date 2013年8月16日 下午5:18:54
	 * @return
	 */
//	@RequestMapping(method=RequestMethod.GET)
//	public String toMenuPackage(ModelMap map) {
//		if(null == cache.get("menuPackages")) {
//			List<DTOMenuPackage> menuPackages = menuPackageService.loadAll();
//			map.addAttribute("menuPackages", menuPackages);
//			cache.put(new Element("menuPackages", menuPackages));
//		} else {
//			map.addAttribute("menuPackages",cache.get("menuPackages").getValue());
//		}
//		return "backend/system/menuPackage";
//	}
	
	/**
	 * <pre>加载菜单包，用于添加资源</pre>
	 * @Auther 郑兴(zhengxing)
	 * @date 2013年8月17日 下午4:01:57
	 * @return
	 */
	@RequestMapping("forResource")
	@ResponseBody
	public List<DTOMenuPackage> loadMenuPackagesForResource() {
		List<DTOMenuPackage> menuPackages = null;
		if(null == cache.get("menuPackages")) {
			menuPackages = menuPackageService.loadAll();
			cache.put(new Element("menuPackages", menuPackages));
		} else {
			menuPackages = (List<DTOMenuPackage>)cache.get("menuPackages").getValue();
		}
		return menuPackages;
	}
	
	/**
	 * <pre>添加菜单包</pre>
	 * @Auther 郑兴(zhengxing)
	 * @date 2013年8月16日 下午5:21:08
	 * @return
	 */
	@RequestMapping("/add")
	@ResponseBody
	public Object addMenuPackage(@ModelAttribute("menuPackage")DTOMenuPackage dto) {
		try {
			if(null == dto.getStatus()) {
				dto.setStatus(PackageStatus.SHOW);
			}
			menuPackageService.saveOrUpdate(dto);
			//更新缓存
			cache.put(new Element("menuPackages", menuPackageService.loadAll()));
			return "success";
		} catch (Exception e) {
			log.error("Save MenuPackage error.", e);
		}
		return "fail";
	}
	
	@RequestMapping("/{id}")
	@ResponseBody
	public DTOMenuPackage loadMenuPackage(@PathVariable("id")Long id) {
		return menuPackageService.find(id);
	}
}
